package com.jettech.oa.web.admin;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.jettech.oa.common.ConstType;
import com.jettech.oa.domain.WorkFlow;
import com.jettech.oa.service.WorkFlowService;
import com.jettech.oa.utils.PageUtil;

@Controller
@RequestMapping(value="/system/workflow")
public class WorkFlowController {
	@Autowired
	private WorkFlowService workFlowService;
	
	@RequestMapping(value="/list",method=RequestMethod.GET)
	public String list(Model model){
		PageUtil pageUtil = new PageUtil();
		pageUtil.setCurPage(1);
		List<WorkFlow> list = workFlowService.findWorkFlowList(pageUtil);
		model.addAttribute("list",list);
		return "system/workflow/list";
	}

	@RequestMapping(value="/manage",method=RequestMethod.POST)
	public String manage(@RequestParam int curPage,@RequestParam int perPageRow,Model model){
		PageUtil pageUtil = new PageUtil();
		pageUtil.setCurPage(curPage);
		pageUtil.setPerPageRow(perPageRow);
		workFlowService.findWorkFlowList(pageUtil);
		return "system/workflow/list";
	}
	
	@RequestMapping(method=RequestMethod.GET)
	public String toCreate(){
		return "system/workflow/createForm";
	}
	
	@RequestMapping(method=RequestMethod.POST)
	public String create(@ModelAttribute WorkFlow workFlow, BindingResult result,
			@RequestParam MultipartFile processDefinedFile,@RequestParam MultipartFile processDefinedImage,
			HttpServletRequest request){
		HttpSession session = request.getSession();
		com.jettech.oa.domain.User user = (com.jettech.oa.domain.User)session.getAttribute(ConstType.ADMIN_SESSION_USER);

		workFlow.setUser(user);
		Date createdTime = new Date();
		workFlow.setCreatedTime(createdTime);
		workFlow.setUpdatedTime(createdTime);
		if(processDefinedFile!=null){
			try {
				workFlow.setProcessDefinedFile(processDefinedFile.getBytes());
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if(processDefinedImage!=null){
			try {
				workFlow.setProcessDefinedImage(processDefinedImage.getBytes());
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		workFlowService.saveOrUpdateWorkFlow(workFlow);
		return "redirect:/system/workflow/list";
	}
}
